extends "res://tanks/Tank.gd"

var target_list := []

func control(delta):
	$Turret.look_at(get_global_mouse_position())
	var rot = Input.get_action_strength("turn_right") - Input.get_action_strength("turn_left")
	rotation += rot * rotation_speed * delta
	velocity = Vector2.ZERO
	if Input.is_action_pressed("forward"):
		velocity = Vector2(max_speed, 0).rotated(rotation)
	elif Input.is_action_pressed("back"):
		velocity = Vector2(-max_speed, 0).rotated(rotation) / 2
	if Input.is_action_just_pressed("click"):
		#移除无效的目标（已被删除），倒着遍历
		for i in range(target_list.size() - 1, -1, -1):
			if not is_instance_valid(target_list[i]):
				target_list.remove(i)
		#锁定最近的敌人
		var target = null
		if not target_list.empty():
			target = target_list[0]
			for i in range(1, target_list.size()):
				var dist = position.distance_squared_to(target_list[i].global_position)
				if dist < position.distance_squared_to(target.global_position):
					target = target_list[i]
		shoot(gun_shots, gun_spread, target)


func _on_Detector_body_entered(body):
	target_list.append(body)

func _on_Detector_body_exited(body):
	target_list.remove(target_list.find(body))
